﻿function AzureOnlineNewRequestView(context) {

    var verb = ko.observable('GET');
    var protocol = ko.observable('https');
    var host = ko.observable('');
    var path = ko.observable('/');
    var version = ko.observable('');
    var authorization = ko.observable('');
    var leaseAction = ko.observable('');
    
    var comp = ko.observable('');
    var timeout = ko.observable('');
    var headers = {};
    var queries = {};
    var data = ko.observable(null);
    var template = ko.observable();


    var request = ko.observable(new AzureRequest());
    
    var hasLeaseAction = ko.computed(function() {
        switch (template()) {
            case 'blobs.leaseBlob':
            case 'blobs.leaseContainer':
                return true;
        }
        return false;
    });
    
    var lastExecuted = ko.observable(null);

    var tablesHost = ko.computed(function () {
        return context.accounts.accountName() + '.table.core.windows.net';
    });

    var blobsHost = ko.computed(function () {
        return context.accounts.accountName() + '.blob.core.windows.net';
    });

    var queuesHost = ko.computed(function () {
        return context.accounts.accountName() + '.queue.core.windows.net';
    });

    var settings = ko.computed(function () {
        return context.accountSettings().folder('console').folder('newRequest');
    });

    ko.computed(function () {
        var s = settings();
        template(s.getItem('template') || 'blobs.listContainers');
        utils.async(applyTemplate);
    });

    template.subscribe(function () {
        settings().setItem('template', template());
    });

    function fromRequest(req) {
        var url = req.uri;
        var reqProtocol = url.getProtocol();
        verb(req.verb);
        if (reqProtocol.length > 3) {
            protocol(reqProtocol.substr(0, reqProtocol.length - 3));
        }
        host(url.getHost());
        path(url.getPath());

        authorization(req.signatureType);

        comp(req.getQuery('comp') || '');
        timeout(req.getQuery('timeout') || '');

        data(req.data);

        request(req);
        
        headers = {};
        for (var header in req.headers) {
            headers[header] = req.headers[header];
        }

        version(req.headers['x-ms-version']);

        queries = {};
        for (var query in req.query) {
            queries[query] = req.query[query];
        }
    }

    function applyTemplate() {
        var api = context.api();
        if (!api) return;
        switch (template()) {
            case 'tables.queryTables':
                fromRequest(api.tables.requests.queryTables({
                }));
                break;
            case 'tables.createTable':
                fromRequest(api.tables.requests.createTable({
                    content: ''
                }));
                break;
            case 'tables.deleteTable':
                fromRequest(api.tables.requests.deleteTable({
                    table: '{table}'
                }));
                break;
            case 'tables.query':
                fromRequest(api.tables.requests.query({
                    table: '{table}'
                }));
                break;
            case 'tables.deleteEntity':
                fromRequest(api.tables.requests.deleteEntity({
                    partitionKey: '{partitionKey}',
                    rowKey: '{rowKey}',
                    table: '{table}'
                }));
                break;
            case 'blobs.createContainer':
                fromRequest(api.blob.requests.createContainer({
                    container: '{container}'
                }));
                break;
            case 'blobs.listContainers':
                fromRequest(api.blob.requests.listContainers({}));
                break;
            case 'blobs.leaseContainer':
                fromRequest(api.blob.requests.leaseContainer({
                    container: '{container}',
                    duration: 60
                }));
                break;
            case 'blobs.deleteContainer':
                fromRequest(api.blob.requests.deleteContainer({
                    container: '{container}'
                }));
                break;
            case 'blobs.listBlobs':
                fromRequest(api.blob.requests.listBlobs({
                    container: '{container}'
                }));
                break;
            case 'blobs.getBlob':
                fromRequest(api.blob.requests.getBlob({
                    container: '{container}',
                    blob: '{blobName}'
                }));
                break;
            case 'blobs.leaseBlob':
                fromRequest(api.blob.requests.leaseBlob({
                    container: '{container}',
                    blob: '{blobName}'
                }));
                leaseAction('acquire');
                break;
            case 'blobs.deleteBlob':
                fromRequest(api.blob.requests.deleteBlob({
                    container: '{container}',
                    blob: '{blobName}'
                }));
                break;
            case 'queues.create':
                fromRequest(api.queues.requests.createQueue({
                    queue: '{queue}'
                }));
                break;
            case 'queues.list':
                fromRequest(api.queues.requests.list({}));
                break;
            case 'queues.delete':
                fromRequest(api.queues.requests.deleteQueue({
                    queue: '{queue}'
                }));
                break;
            case 'queues.getMessages':
                fromRequest(api.queues.requests.getMessages({
                    queue: '{queue}',
                    visibilityTimeout: 1
                }));
                break;
            case 'queues.peekMessages':
                fromRequest(api.queues.requests.peekMessages({
                    queue: '{queue}'
                }));
                break;
        }
    }

    template.subscribe(applyTemplate);

    this.tablesHost = tablesHost;

    this.blobsHost = blobsHost;

    this.queuesHost = queuesHost;


    var record = ko.observable(new AzureOnlineLoggingRecord(request()));

    ko.computed(function () {
        var req = request();
        var p = path();
        if (p.charAt(0) != '/') p = '/' + p;
        req.verb = verb();
        var url = protocol() + '://' + host() + p;
        req.uri = new Uri().parse(url);
        refreshRequest();
    });

    ko.computed(function () {
        var req = request();
        req.headers['x-ms-version'] = version();
        refreshRequest();
    });
    
    ko.computed(function () {
        var req = request();
        req.signatureType = authorization();
        refreshRequest();
    });
    
    ko.computed(function () {
        var req = request();
        var c = comp();
        if (c) req.addQuery('comp', c);
        refreshRequest();
    });
    
    ko.computed(function () {
        var req = request();
        var t = timeout();
        if (t) req.addQuery('timeout', t);
        refreshRequest();
    });
    
    ko.computed(function () {
        var req = request();
        var action = leaseAction();
        if (hasLeaseAction() && action) {
            req.headers['x-ms-lease-action'] = action;
        } else {
            delete req.headers['x-ms-lease-action'];
        }
        refreshRequest();
    });
    
    function refreshRequest() {
        var req = request();
        req.refreshDate();
        var api = context.api();
        if (api) {
            req.sign(api.getCredentials());
        }
        
        record(new AzureOnlineLoggingRecord(req));
    }
    
    function execute() {
        refreshRequest();
        
        var req = request();
        
        var api = context.api();
        api.execute(req, {});
        lastExecuted(context.channel.requests()[0]);
    }

    this.verb = verb;
    this.protocol = protocol;
    this.host = host;
    this.path = path;
    this.comp = comp;
    this.timeout = timeout;
    this.version = version;
    this.authorization = authorization;
    this.context = context;
    this.request = request;
    this.record = record;
    this.template = template;
    this.applyTemplate = applyTemplate;
    this.execute = execute;
    this.lastExecuted = lastExecuted;
    this.leaseAction = leaseAction;
    this.hasLeaseAction = hasLeaseAction;
}